package com.tianbing.adlottery.util;

/**
 * Utility to assist converting between a MD5 byte[] and Hex String value.
 * 
 * @author Carl Trusiak
 */
public class MD5Util {
	/**
	 * Creates a new instance of MD5Util
	 */
	private MD5Util() {
	}

	/**
	 * Converts the byte[] returned from MD5 to a Hex String
	 * 
	 * @param b
	 *            MD5 byte[]
	 * 
	 * @return String Hex String
	 */
	public static String MD5ByteArrayToHexString(byte b[]) {
		StringBuffer sb = new StringBuffer(32);
		for (int i = 0; i < b.length; i++) {
			// we are only interested in the last 8 bits. & this with 255
			// ensures that is all we get.
			int j = b[i] & 255;

			String s = Integer.toHexString(j);

			// We want each one to be bothe characters. interface if it's f, we
			// want 0f
			if (s.length() == 1) {
				s = "0" + s;
			}
			sb.append(s);
		}

		return sb.toString();
	}

	/**
	 * Converts a Hex String back to a byte[]
	 * 
	 * @param s
	 *            String value of a MD5
	 * 
	 * @return MD5 byte[]
	 */
	public static byte[] MD5HexStringToByteArray(String s) {
		// the String should be 32 characters long. if not prepad it with 0's
		if (s.length() < 32) {
			s = "00000000000000000000000000000000" + s;
			s = s.substring(s.length() - 32);
		}

		byte b[] = new byte[s.length() / 2];
		for (int i = 0; i < b.length; i++) {
			// parse each 2 characters of the string as hex values.
			b[i] = (byte) Integer.parseInt(s.substring(i * 2, (i * 2) + 2), 16);
		}

		return b;
	}

}